﻿using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using System.Web;
using WaveringLand_Launcher.Helper.Common;
using WaveringLand_Launcher.Model;

namespace WaveringLand_Launcher.Helper.Net
{
    public class WlApiHelper
    {
        private const string server = "http://api.heerdev.top/wlapi";

        public const string indexurl = server +"/game";
        public const string launcher_verison_url = server + "/launcher";
        public const string news_url = server +"/news";

        public static async Task<List<WllFile>> GetFileIndexAsync()
        {
            var url = indexurl;
            var httpc = new HttpClient();
            var result = await httpc.GetStringAsync(url);
            httpc.Dispose();
            return JsonSerializer.Deserialize<List<WllFile>>(result);
        }

        public static string GetLauncherVersion()
        {
            var url = launcher_verison_url;
            var httpc = new HttpClient();
            var result = httpc.GetStringAsync(url).Result;
            return result;
        }

        public static List<WllFile> GetNews()
        {
            var url = news_url;
            var httpc = new HttpClient();
            var result = httpc.GetStringAsync(url).Result;
            return JsonSerializer.Deserialize<List<WllFile>>(result);
        }

        public static async Task<List<KeyValuePair<string, string>>> GetLackFiles()
        {
            List<KeyValuePair<string, string>> list = new();
            var index = await WlApiHelper.GetFileIndexAsync();
            var url = "";
            foreach (var item in index)
            {
                if (item.Url == "")
                {
                    url = HttpUtility.UrlEncode($"{PathHelper.DownloadServer}/{item.Path}");
                }
                else
                {
                    url = item.Url;
                }

                var localpath = Path.Combine(Directory.GetCurrentDirectory(), item.Path);
                if (Directory.Exists(Path.GetDirectoryName(localpath)) is false)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(localpath));
                }
                if (File.Exists(localpath) is false)
                {
                    list.Add(new(localpath, url));
                    continue;
                }
                if (Md5Helper.GetMd5(localpath) != item.MD5)
                {
                    list.Add(new(localpath, url));
                    continue;
                }
            }
            return list;
        }
    }
}